package com.copc.common.domain;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @Author liubo
 * @Date 2022-11-01 10:49
 */
@Slf4j
public class ExcelUtil {

    public static void exportExcel(List objects, Class clazz, String fileName, String sheetName){
        if (ObjectUtil.isEmpty(objects)) {
            return;
        }
        try {
            ServletRequestAttributes servletRequestAttributes =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletResponse response = servletRequestAttributes.getResponse();
            // 设置响应头
            response.setContentType("application/vnd.ms-excel" );
            response.setCharacterEncoding("utf-8" );
            // 设置防止中文名乱码
            String exportName = URLEncoder.encode(fileName, "utf-8" );
            String sheetSubName = URLEncoder.encode(sheetName, "utf-8" );
            // 文件下载方式(附件下载还是在当前浏览器打开)
            response.setHeader("Content-disposition", "attachment;filename=" + exportName + ".xlsx" );
            // 向Excel中写入数据
            EasyExcel.write(response.getOutputStream(), clazz)
                    .sheet(sheetSubName)
                    .doWrite(objects);
        }catch (Exception e){
            log.error(fileName,e);
            throw new RuntimeException(fileName+"导出失败");
        }

    }

    public static void exportExcel(List objects, Class clazz, String fileName) {
        exportExcel(objects,clazz,fileName,"sheet1");
    }
    public static void exportExcel(List objects, String fileName) {
        if (ObjectUtil.isEmpty(objects)) {
            return;
        }
        Class clazz = objects.get(0).getClass();
        exportExcel(objects,clazz,fileName,"sheet1");
    }

}
